package first.niuke.huawei.mediumDifficulty;

import java.util.Scanner;

/**
 * @ClassName HJ48
 * @description:
 * @author: 荣燊
 * @create: 2021-07-14 10:04
 **/
public class HJ48 {
    // 从单向链表中删除指定值的节点

    static Node head;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int length = scanner.nextInt();
            int head_val = scanner.nextInt();

            head = new Node(head_val);

            for (int i=0; i<length-1; i++) {
                int a = scanner.nextInt();
                int b = scanner.nextInt();
                // 构造链表
                insert(a, b);
            }

            // 删除指定节点操作
            int c = scanner.nextInt();
            delete(c);

            // 打印链表
            while (head != null) {
                System.out.print(head.val+" ");
                head = head.next;
            }
        }
    }

    // 链表插入函数,第2个节点值后面插入第1个节点值
    static void insert(int a, int b) {
        Node tmp_node = head;
        Node insert_node = new Node(a);
        while (tmp_node != null) {
            if (tmp_node.val == b) {
                Node nextNode = tmp_node.next;
                tmp_node.next = insert_node;
                insert_node.next = nextNode;
                break;
            } else {
                tmp_node = tmp_node.next;
            }
        }
    }

    // 链表删除函数
    static void delete(int a) {
        Node preNode = head;
        Node nextNode = head.next;
        // 直接删除第一个节点
        if (preNode.val == a) {
            head = null;
        }

        while (nextNode != null) {
            if (nextNode.val == a) {
                preNode.next = nextNode.next;
                break;
            } else {
                preNode = preNode.next;
                nextNode = nextNode.next;
            }
        }
    }

    static class Node {
        int val;
        Node next;
        Node(int val) {
            this.val = val;
        }
    }
}
